package client;

import capsules.CapsuleSpecification;
import capsules.CapsuleState;
import communication.Connection;
import communication.ConnectionException;
import server.ServerState;

public class RarcServer {


	private Connection conn;


	public RarcServer(Connection conn)
    throws ConnectionException{
		this.conn = conn;
	}
	
	
	public boolean login(Identifier identifier)
    throws ConnectionException{
		conn.send(Operation.LOGIN);
		conn.send(identifier);
        conn.flush();

		return conn.receiveBoolean();
	}


	public void logout()
    throws ConnectionException{
		conn.send(Operation.LOGOUT);
        conn.flush();
	}


	public ServerState getServerState()
    throws ConnectionException{
		conn.send(Operation.VERIFY_STATE_SERVER);
        conn.flush();

		return (ServerState) conn.receiveObject();
	}


    public void sendOfferedSpace(long offeredSpace)
    throws ConnectionException {
		conn.send(Operation.SEND_OFFERED_SPACE);
		conn.send(offeredSpace);
        conn.flush();
	}


    public void sendConfiguration(Configuration configuration)
    throws ConnectionException {
		conn.send(Operation.SEND_CONFIGURATION);
		conn.send(configuration);
        conn.flush();
	}


	public CapsuleSpecification getCapsuleSpecification()
    throws ConnectionException{
		conn.send(Operation.ASK_CAPSULE_SPECIFICATION);
        conn.flush();

		return (CapsuleSpecification) conn.receiveObject();
	} 


	public CapsuleState getCapsuleState(CapsuleSpecification capsuleSpecification)
    throws ConnectionException{
		conn.send(Operation.VERIFY_STATE_CAPSULE);
		conn.send(capsuleSpecification);
        conn.flush();

		return (CapsuleState) conn.receiveObject();
	}


	public void downloadCapsule(String nameCapsule, long offset)
    throws ConnectionException {
		conn.send(Operation.DOWNLOAD_CAPSULE);
		conn.send(nameCapsule);
		conn.send(offset);
        conn.flush();
	}
	
	
	public int getCapsuleBytes(byte [] buffer)
    throws ConnectionException {
		return (int) conn.receiveBytes(buffer);
	}
	
	
	public boolean verifyUploadCapsule(String nameCapsule)
    throws ConnectionException{
		conn.send(Operation.VERIFY_UPLOAD_CAPSULE);
		conn.send(nameCapsule);
        conn.flush();

		return (boolean) conn.receiveBoolean();
	}

    
    public long uploadCapsule(String nameCapsule)
    throws ConnectionException{
		conn.send(Operation.UPLOAD_CAPSULE);
		conn.send(nameCapsule);
        conn.flush();

		return (long) conn.receiveLong();
	}
	
	
	public void sendCapsuleBytes(byte [] buffer,int init, int length)
    throws ConnectionException {
		conn.send(buffer, init, length);
	}

    
}
